<template>
  <div>
    <e-container>
      <e-title :title="computedTitle" />
      <a-divider />
      <div class="form">
        <a-row v-if="action === 'add' && briefInfo.phaseID > 1" style="margin-bottom: 16px">
          <a-col :span="24">
            <e-checkbox v-model="apiData.isNextPhase" @change="checkNextPhaseAvailable">
              Progress has been made, Go to the Phase {{ briefInfo.phaseID - 1 }}.
            </e-checkbox>
          </a-col>
        </a-row>
        <a-row v-else-if="action === 'restart'" style="margin-bottom: 16px">
          <a-col :span="24">
            <span class="tips">
              Tips: This Operation will take you back to phase 3, all previous communication records can be viewed in
              [Other Records].
            </span>
          </a-col>
        </a-row>
        <a-spin :spinning="loading">
          <a-form ref="formInstance" :model="apiData" layout="vertical" :rules="rules">
            <a-row v-if="action === 'restart'" :gutter="gutter">
              <a-col :span="24">
                <a-form-item label="Reason" name="reason">
                  <a-textarea v-model:value="apiData.reason" :auto-size="{ minRows: 4, maxRows: 4 }" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-divider v-if="action === 'restart'" dashed />
            <a-row :gutter="gutter" style="position: relative">
              <a-col :span="24">
                <a-form-item label="Contacts" name="contactIDS">
                  <a-select
                    v-model:value="apiData.contactIDS"
                    mode="multiple"
                    :get-popup-container="triggerNode => triggerNode.parentNode"
                  >
                    <a-select-option v-for="item in contacts" :key="item.id">
                      <a-space>
                        {{ item.contactName }}<span style="color: #bfbfbf"> {{ item.emai }} </span>
                      </a-space>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!-- 新增联系人
            <div
              style="position: absolute; right: 26px; top: 36px; cursor: pointer"
              @click="addContactModalShow = true">
              <e-icon type="add" font-size="24px" color="#3c6cfe" />
            </div>
            -->
            </a-row>
            <a-row :gutter="gutter">
              <a-col :span="12">
                <a-form-item label="Communication Method" name="CommunicationMethod">
                  <a-select
                    v-model:value="apiData.CommunicationMethod"
                    :get-popup-container="triggerNode => triggerNode.parentNode"
                  >
                    <a-select-option v-for="item in dict.communicationMethods" :key="item.value">
                      {{ item.text }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="Communication Time" name="CommunicationTime">
                  <a-date-picker
                    v-model:value="apiData.CommunicationTime"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disabledDate"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="gutter">
              <a-col :span="12">
                <a-form-item label="Communication Category" name="CommunicationCategory">
                  <a-select
                    v-model:value="apiData.CommunicationCategory"
                    :get-popup-container="triggerNode => triggerNode.parentNode"
                  >
                    <a-select-option v-for="item in dict.communicationCategories" :key="item.text">
                      {{ item.text }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item name="fileName">
                  <template #label>
                    Attachment
                    <a-tooltip v-if="isRevivalClient">
                      <template #title> Extend MSA, and upload proof of communication. </template>
                      <e-icon type="tips1" style="cursor: help; margin-left: 6px; font-size: 16px; color: orange" />
                    </a-tooltip>
                  </template>
                  <a-input :value="fileName" :readonly="true">
                    <template #addonAfter>
                      <input v-show="false" ref="uploadInput" type="file" @change="uploadFileChange" />
                      <span style="color: #a9b5c9; cursor: pointer" @click="uploadInput.click()">
                        <e-icon type="upload" style="margin-right: 6px" />Upload
                      </span>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="gutter">
              <a-col :span="24">
                <a-form-item label="Communication Subject" name="CommunicationSubject">
                  <a-textarea v-model:value="apiData.CommunicationSubject" :auto-size="{ minRows: 4, maxRows: 4 }" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="gutter">
              <a-col :span="24">
                <a-form-item label="Next Communication" name="NextCommunication">
                  <a-input v-model:value="apiData.NextCommunication" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-spin>
        <a-divider />
        <div class="buttons">
          <a-space size="middle">
            <a-button @click="handleClientCancel">Cancel</a-button>
            <a-button
              v-if="!briefInfo.isExisting || action === 'restart' || revivalClient"
              type="primary"
              :disabled="loading"
              @click="handleClientSave"
            >
              Save
            </a-button>
          </a-space>
        </div>
      </div>
    </e-container>
    <a-modal
      v-model:visible="addContactModalShow"
      wrap-class-name="full-screen-modal"
      :closable="false"
      :footer="null"
      :destroy-on-close="true"
    >
      <add-contact
        :referenced="true"
        :params="{ action: 'create', id: id }"
        @cancel="addContactModalShow = false"
        @updated="handleContactUpdated"
      />
    </a-modal>
    <a-modal
      v-model:visible="showReasonModal"
      :footer="null"
      width="536px"
      title="Operation Failure"
      wrap-class-name="primary-modal no-padding"
    >
      <span class="tips">Need to add more information :</span>
      <div v-for="(item, index) in unavailableDetail" :key="index" class="block basic-info">
        <span class="title">{{ item.name }}</span>
        <div class="group">
          <div v-for="(reason, subIndex) in item.resonList" :key="subIndex" class="reason">
            <a-space>
              <e-icon
                :type="reason.level === 0 ? 'error1' : 'tips1'"
                :color="reason.level === 0 ? '#fc4b3b' : '#FFA724'"
              />
              {{ reason.itemName }}
            </a-space>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { computed, reactive, ref, inject } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import {
  CHECK_FORM_INTEGRITY,
  CONFIRM_BACK_TO_DETAIL,
  PROGRESS_ACTIVATED,
  PROGRESS_RESTART,
  TOUCH_RECORD_ADDED,
  TOUCH_RECORD_UPDATED,
  UPLOAD_FAILED
} from '@/constants/message.js'
import EContainer from '@/components/EContainer.vue'
import EIcon from '@/components/EIcon.vue'
import ETitle from '@/components/ETitle.vue'
import ECheckbox from '@/components/ECheckbox.vue'
import AddContact from '../contact/createOrEdit.vue'
import PhaseProgress from '@/api/client/phaseProgress.js'
import TargetClient from '@/api/targetClient.js'
import dayjs from 'dayjs'
const { Modal, message } = inject('Feedback')
const route = useRoute()
const router = useRouter()
const { id, action } = route.params
const store = useStore()
const apiData = reactive({
  contactIDS: [],
  CommunicationMethod: '',
  CommunicationCategory: '',
  // 联系时间
  CommunicationTime: null,
  CommunicationSubject: '',
  NextCommunication: '',
  AttachmentAddr: '',
  AttachmentFileSize: '',
  AttachmentName: '',
  isNextPhase: false
})
const fileName = ref('')
const computedTitle = computed(() => {
  if (action === 'add' || action === 'activate') {
    return 'Add Communication Record'
  } else if (action === 'edit') {
    return 'Edit Communication Record'
  } else {
    return 'Restart'
  }
})
const briefInfo = computed(() => store.state.client.briefInfo)
// 是二次开发
const isRevivalClient = computed(() => briefInfo.value.reconnectStatus === 20)
// 二次开发进行中状态
const revivalClient = computed(() => briefInfo.value.reconnectStatus === 25)
const formInstance = ref(null)
const uploadInput = ref(null)
const loading = ref(false)
const gutter = [120, 16]
const contacts = ref([])
const addContactModalShow = ref(false)
const rules = {
  reason: [
    {
      required: true,
      whitespace: true,
      message: 'Please input reason',
      trigger: 'blur'
    }
  ],
  contactIDS: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least one contact',
      trigger: 'blur'
    }
  ],
  CommunicationMethod: [
    {
      type: 'number',
      required: true,
      message: 'Please select a communication method',
      trigger: 'blur'
    }
  ],
  CommunicationTime: [
    {
      required: true,
      message: 'Please select the communication time',
      trigger: 'blur'
    }
  ],
  CommunicationCategory: [
    {
      required: true,
      message: 'Please select a communication category',
      trigger: 'blur'
    }
  ],
  CommunicationSubject: [
    {
      required: true,
      whitespace: true,
      message: 'Please input communication subject',
      trigger: 'blur'
    }
  ],
  NextCommunication: [
    {
      required: true,
      whitespace: true,
      message: 'Please input next communication',
      trigger: 'blur'
    }
  ],
  fileName: [
    {
      required: true,
      validator: () => {
        return fileName.value ? Promise.resolve() : Promise.reject(new Error())
      },
      message: 'Please upload attachment',
      trigger: 'change'
    }
  ]
}
const disabledDate = current => {
  return current > dayjs().endOf('day')
}
const dict = ref(computed(() => store.state.dict))
if (action === 'restart') {
  document.title = 'Restart'
}
if (action === 'add') {
  store.dispatch('dict/getCommunicationMethods').then(() => {
    if (dict.value.communicationMethods.length > 0) {
      apiData.CommunicationMethod = dict.value.communicationMethods[0].value
    }
  })
  store.dispatch('dict/getCommunicationCategories').then(() => {
    if (dict.value.communicationCategories.length > 0) {
      apiData.CommunicationCategory = dict.value.communicationCategories[0].text
    }
  })
}
if (action === 'edit') {
  document.title = 'Edit Communication Record'
  const { leadId, recordId } = route.params
  loading.value = true
  PhaseProgress.getTouchRecord(leadId, recordId).then(({ data }) => {
    apiData.contactIDS = data.contactIDS
    apiData.CommunicationMethod = data.communicationMethod
    apiData.CommunicationCategory = data.communicationCategory
    apiData.CommunicationTime = dayjs(data.communicationTime).format('YYYY-MM-DD')
    apiData.CommunicationSubject = data.communicationSubject
    apiData.attachment = data.attachment
    apiData.AttachmentAddr = data.attachmentAddr
    apiData.AttachmentFileSize = 0
    apiData.AttachmentName = data.attachmentName
    apiData.NextCommunication = data.nextCommunication
    fileName.value = data.attachmentName
    loading.value = false
  })
}
PhaseProgress.getClientContacts(id).then(res => {
  contacts.value = res.data
})
// 添加记录时自动带出联系人
if (action === 'add') {
  PhaseProgress.getLastContact(id).then(({ data }) => {
    if (Array.isArray(data)) {
      apiData.contactIDS = data.map(item => item.value)
    }
  })
}
const showReasonModal = ref(false)
const unavailableDetail = ref([])
const checkNextPhaseAvailable = checked => {
  if (checked) {
    PhaseProgress.checkNextPhaseIsAvailable(id).then(({ data }) => {
      apiData.isNextPhase = data.isAllow
      // 不能通过或者有警告的项目则弹出窗口
      showReasonModal.value =
        !data.isAllow || (Array.isArray(data.transitFailResons) && data.transitFailResons.length > 0)
      unavailableDetail.value = data.transitFailResons
    })
  }
}
const uploadFileChange = event => {
  if (event.target.files.length > 0) {
    TargetClient.uploadFiles(event.target.files)
      .then(res => {
        if (Array.isArray(res) && res.length > 0 && res[0] instanceof Eci.IO.File) {
          fileName.value = event.target.files.length > 0 ? event.target.files[0].name : ''
          apiData.AttachmentAddr = res[0].Path
          apiData.AttachmentFileSize = res[0].SourceBaseFileSize
          apiData.AttachmentName = fileName.value
          apiData.attachment = 0
          formInstance.value.clearValidate('fileName')
        } else {
          fileName.value = ''
          message.error(UPLOAD_FAILED)
        }
      })
      .catch(() => {
        fileName.value = ''
        uploadInput.value.value = null
        message.error(UPLOAD_FAILED)
      })
  }
}
const handleClientCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push({ name: 'Phase Progress', params: { id: id } })
    }
  })
}
const emits = defineEmits(['updated'])
const handleClientSave = () => {
  formInstance.value
    .validate()
    .then(() => {
      loading.value = true
      if (action === 'add') {
        PhaseProgress.addTouchRecord(id, apiData)
          .then(() => {
            emits('updated')
            message.success(TOUCH_RECORD_ADDED)
            router.push({ name: 'Phase Progress', params: { id: id } })
          })
          .finally(() => {
            loading.value = false
          })
      } else if (action === 'edit') {
        const { recordId } = route.params
        PhaseProgress.updateTouchRecord(id, recordId, apiData)
          .then(() => {
            emits('updated')
            message.success(TOUCH_RECORD_UPDATED)
            router.push({ name: 'Phase Progress', params: { id: id } })
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        PhaseProgress.restart(id, apiData)
          .then(() => {
            emits('updated', action)
            if (action === 'restart') {
              message.success(PROGRESS_RESTART)
            }
            if (action === 'activate') {
              message.success(PROGRESS_ACTIVATED)
            }
            router.push({ name: 'Phase Progress', params: { id: id } })
          })
          .finally(() => {
            loading.value = false
          })
      }
    })
    .catch(() => {
      message.error(CHECK_FORM_INTEGRITY)
    })
}
const handleContactUpdated = () => {
  addContactModalShow.value = false
  PhaseProgress.getClientContacts(id).then(res => {
    contacts.value = res.data
  })
}
</script>

<style lang="less" scoped>
.tips {
  color: @text-gray;
}
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
</style>
<style lang="less">
.no-padding {
  .ant-modal-body {
    padding: 0 0 48px 0 !important;
    .tips {
      display: inline-block;
      padding: 24px 24px 0 24px;
    }
    .block {
      margin-left: 80px;
      padding: 24px 0;
      border-bottom: 1px solid @border-color;
      .title {
        display: inline-block;
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 24px;
      }
      .group {
        .reason {
          margin-top: 16px;
        }
        &:last-child {
          .ant-divider {
            display: none;
          }
        }
      }
    }
  }
}
</style>
<route lang="yaml">
name: Add Communication Record
path: '/client/:id/phase-progress/:action/:leadId?/:recordId?'
meta:
  title: Add Communication Record
  permission: PhaseProgress
</route>
